package com.xiangdao.controller;

import com.xiangdao.dao.MessageDao;
import com.xiangdao.dao.PostMainDao;
import com.xiangdao.dao.ShareProductDao;
import com.xiangdao.dao.UserDao;
import com.xiangdao.model.PageBean;
import com.xiangdao.model.PostMain;
import com.xiangdao.model.ShareProduct;
import com.xiangdao.model.User;
import com.xiangdao.service.PageService;
import com.xiangdao.service.ShareProductService;
import com.xiangdao.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ShareProductController {
    @Autowired
    UserDao userDao;
    @Autowired
    ShareProductService shareProductService;
    @Autowired
    PageService pageService;

    @Autowired
    ShareProductDao shareProductDao;
    @Autowired
    HostHolder hostHolder;

    @Autowired
    PostMainDao postMainDao;

    @Autowired
    MessageDao messageDao;

    @RequestMapping(path = "/uploadwindow",method = RequestMethod.GET)
    public String displayuploadwindow() {
        return "/uploadwindow";
    }
    @RequestMapping(path = "/addProduct", method = RequestMethod.POST)
    public View addShareProduct(@RequestParam("rname") String title,
                                @RequestParam("rdetails") String message, @RequestParam("rprice") String price,
                                @RequestParam("ruserid") String user_name, @RequestParam("file") MultipartFile pic, HttpServletRequest request, HttpSession session) {
        ShareProduct shareProduct = new ShareProduct();
        shareProduct.setTitle(title);
        try {
            shareProduct.setPrice(Double.valueOf(price));
        }catch (Exception e){
            System.out.println("错误");
        }
        shareProduct.setMessage(message);
        Integer user_id=userDao.getIdByUsername(user_name);
        shareProduct.setUser_id(user_id);
//        Date date= new Date(System.currentTimeMillis());
//        String pattern="yyyy/MM/dd HH时mm分ss秒";
//        SimpleDateFormat sdf= new SimpleDateFormat(pattern);
        shareProduct.setTime(new Date());

        shareProduct.setUser(userDao.getUserById(user_id));




        //获取文件在服务器的储存位置
        String path = "D:\\ASUS\\IdeaProjects\\xiangdao_web\\xiangdao\\src\\main\\resources\\static\\images\\new";
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }
        //获取原始文件名称(包含格式)
        String originalFileName = pic.getOriginalFilename();
        //获取文件类型，以最后一个`.`为标识
        assert originalFileName != null;
        //获取文件名称（不包含格式）
//        String name = originalFileName.substring(originalFileName.lastIndexOf("/") + 1);
        String fileName = UUID.randomUUID() + ".jpg";
        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        String s=targetFile.getName();
        if(targetFile.length()<1){
            s="wu.jpeg";
        }
        shareProduct.setImage(s);
        shareProductDao.addProduct(shareProduct);
        String contextPath = request.getContextPath();
        //将文件保存到服务器指定位置
        try {
            pic.transferTo(targetFile);

            return new RedirectView(contextPath + "/uploadSuccess");
        } catch (IOException e) {
            session.setAttribute("fail","图片保存出现错误，请重试！");
            return null;
        }
//        return new RedirectView(contextPath + "/find/1");
    }
    @RequestMapping(path = "/uploadSuccess",method = RequestMethod.GET)
    public String displayuploadSuccess() {
        return "/uploadSuccess";
    }
    @RequestMapping(path = "/find/{currentPage}", method = RequestMethod.GET)
    public String dispalyShareProductPageByPrice(String title, @PathVariable int currentPage, Model model) {
//        PageBean<ShareProduct> pageShareProduct = pageService.findSPItemByPageByPrice(title, currentPage, 10);
//        ArrayList<ShareProduct> pageList = pageShareProduct.getItems();
//        int shareProductsTotalNum = shareProductService.findAllProductByPrice().size();
//        User user=new User();
//        Integer user_id = user.getId();
//        model.addAttribute("user", user);
//        model.addAttribute("shareProducts", pageList);
//        model.addAttribute("shareProductsTotalNum", shareProductsTotalNum);
//        model.addAttribute("userDao", userDao);
//        model.addAttribute("currentPage", pageShareProduct.getCurrentPage());
//        model.addAttribute("totalPage", pageShareProduct.getTotalPage());
//        model.addAttribute("hasNext", pageShareProduct.getIsMore());
//        model.addAttribute("isUserTopicPage", false);
        ArrayList<ShareProduct> shareProducts = shareProductDao.findAllProduct();
        Map<Integer,User> map = new HashMap();
        for (ShareProduct s :
                shareProducts) {
            map.put(s.getId(),userDao.getUserById(s.getUser_id()));
            Integer integer = messageDao.countMessageByShareProduct(s.getId());
            shareProductDao.updateProduct(integer, s.getId());
        }
        ArrayList<ShareProduct> shareProductss = shareProductDao.findAllProduct();
        for (int x=shareProductss.size();x>8;x--){
            shareProductss.remove(x-1);
        }
        model.addAttribute("shareProducts", shareProductss);
        model.addAttribute("userMap", map);
        return "/find";
    }

//    @RequestMapping(path = "/find/{currentPage}", method = RequestMethod.GET)
//    public String dispalyShareProductPage(String title, @PathVariable int currentPage, Model model) {
//        PageBean<ShareProduct> pageShareProduct = pageService.findSPItemByPage(title, currentPage, 10);
//        ArrayList<ShareProduct> pageList = pageShareProduct.getItems();
//        int shareProductsTotalNum = shareProductService.findAllProduct().size();
//        User user=new User();
//        Integer user_id = user.getId();
//        model.addAttribute("user", user);
//        model.addAttribute("shareProducts", pageList);
//        model.addAttribute("shareProductsTotalNum", shareProductsTotalNum);
//        model.addAttribute("userDao", userDao);
//        model.addAttribute("currentPage", pageShareProduct.getCurrentPage());
//        model.addAttribute("totalPage", pageShareProduct.getTotalPage());
//        model.addAttribute("hasNext", pageShareProduct.getIsMore());
//        model.addAttribute("isUserTopicPage", false);
//        return "find";
//    }
    @RequestMapping(path = "/goods/{id}", method = RequestMethod.GET)
    public String displayGdoos(@PathVariable String id, Model model) {
        User user=new User();
        Integer user_id = user.getId();
        ArrayList<ShareProduct> shareProducts =shareProductDao.findAllProduct();

        ShareProduct shareProduct = shareProductDao.findShareProductById(Integer.valueOf(id));
        model.addAttribute("userDao",userDao);
        model.addAttribute("shareProduct",shareProduct);
        model.addAttribute("shareProducts",shareProducts);
        model.addAttribute("user", user);
        model.addAttribute("user_id", user_id);
        return "redirect:/gooods";
    }
}
